package com.example.service;


import com.example.dao.SubjectDao;
import com.example.entity.Subject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
@Transactional
@Slf4j
public class SubjectService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private SubjectDao subjectDao;

    public List<Subject> getAll(){
        return subjectDao.getAll();
    }

    public Subject getOne(int subjectNo){
        String key = "subjectNo-"+subjectNo;
        Subject subject = null;
        if(redisTemplate.hasKey(key)){
            subject = (Subject) redisTemplate.opsForValue().get(key);
            //重置销毁时间
            redisTemplate.expire(key,1,TimeUnit.MINUTES);
            log.info("读取redis:{}",key);
        }else{
            subject = subjectDao.getOne(subjectNo);
            log.info("读取数据库:{}",subjectNo);
            redisTemplate.opsForValue().set(key,subject,1, TimeUnit.MINUTES);
        }
        return subject;
    }

    public int update(Subject subject){
        String key = "subjectNo-"+subject.getSubjectNo();
        redisTemplate.delete(key);
        log.info("删除redis数据:"+key);
        return subjectDao.update2(subject);
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public int add(Subject subject){
        int count = subjectDao.add(subject);
        int a = 5/0;
        subjectDao.add(subject);
        return count;
    }

    public void addOne(){
        subjectDao.add(new Subject("one",100,1));
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public void addTwo(){
        subjectDao.add(new Subject("twoA",201,2));
        int a = 5/0;
        subjectDao.add(new Subject("twoB",202,2));
    }
}
